package com.hs.permission.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hs.admin.client.AdminClient;
import com.hs.common.api.dto.ResultVo;
import com.hs.permission.mapper.PeRoleMapper;
import com.hs.permission.mapper.SsModuleMapper;
import com.hs.permission.pojo.Admin;
import com.hs.permission.pojo.PeRole;
import com.hs.permission.pojo.SsModule;
import com.hs.permission.service.SecurityUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SecurityUserServiceImpl implements SecurityUserService {
 
    @Autowired
    private AdminClient adminClient;
    @Autowired
    private PeRoleMapper roleMapper;
    @Autowired
    private SsModuleMapper moduleMapper;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        ResultVo resultVo = adminClient.findAdminByName(username);
        Admin user = (Admin) resultVo.getData();
        if (user == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }

        // 根据用户查角色
        QueryWrapper<PeRole> roleQueryWrapper = new QueryWrapper<>();
        roleQueryWrapper.eq("user_id",user.getId());
        List<PeRole> roleList = roleMapper.selectList(roleQueryWrapper);

        // 根据用户查权限
        List<SsModule> moduleList =
                moduleMapper.findModuleByUserId(user.getId());

        List<GrantedAuthority> authList = new ArrayList<>();
        if (roleList != null && roleList.size()>0) {
            for (PeRole role : roleList) {
                authList.add(new SimpleGrantedAuthority("ROLE_"+role.getName()));
            }
        }

        if (moduleList != null && moduleList.size()>0) {
            for (SsModule module : moduleList) {
                SimpleGrantedAuthority simple =
                        new SimpleGrantedAuthority(module.getCpermission());
                authList.add(simple);
            }
        }
 
        UserDetails userDetails = new User(user.getUsername(), user.getPassword(), authList);
 
        return userDetails;
    }

}